package com.its.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.its.domain.BaseResult;
import com.its.domain.CodeEnum;
import com.its.manager.pojo.Admin;
import com.its.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/admin")
public class AdminController {
    //新增业务层属性
    @Autowired
    private AdminService adminService;

    @Autowired
    private PasswordEncoder passwordEncoder;//注入密码加密工具


    //声明单元方法：新增管理员
    @PostMapping("/addAdmin")
    public BaseResult<Integer>  addAdmin(@RequestBody Admin admin){
        admin.setPassword(passwordEncoder.encode(admin.getPassword()));//在新增用户的时候将密码直接加密
        return BaseResult.ok(adminService.addAdminService(admin));
    }

    //声明单元方法：修改管理员
    @PostMapping("/updateAdmin")
    public BaseResult<Integer>  updateAdmin(@RequestBody Admin admin){
        admin.setPassword(passwordEncoder.encode(admin.getPassword()));
        return BaseResult.ok(adminService.updateAdminService(admin));
    }

    //声明单元方法：删除管理员
    @DeleteMapping("/deleteAdmin")
    public BaseResult<Integer>  deleteAdmin(Long aid){
        return BaseResult.ok(adminService.deleteAdminService(aid));
    }

    //声明单元方法：根据ID查询管理员
    @GetMapping("/findById")
    public BaseResult<Admin>  selectAdminById(Long aid){
        return BaseResult.ok(adminService.selectAdminByIdService(aid));
    }

    //声明单元方法：分页查询管理员信息
    @GetMapping("/search")
    public BaseResult<Page<Admin>>  getAllAdmin(Integer page, Integer size){
        return BaseResult.ok(adminService.selectAdminByPageService(page, size));
    }

    //声明单元方法：修改管理员角色
    @PutMapping("/updateRoleToAdmin")
    public BaseResult<Void>  updateAdminRole(Long aid,Long[] rids){
        adminService.updateAdminRoleService(aid,rids);
        return BaseResult.ok();
    }

    //声明单元方法：获取登录用户的用户名
//    @GetMapping("/getUsername")
//    public BaseResult<String>  getUsername(){
//        SecurityContext context = SecurityContextHolder.getContext();
//        Authentication authentication = context.getAuthentication();
//        UserDetails userDetails =(UserDetails) authentication.getPrincipal();
//        return BaseResult.ok(userDetails.getUsername());
//    }

}
